/***************************************************************
 * Name:      MortMain.cpp
 * Purpose:   Code for Application Frame
 * Author:    Eusebio Aguilera (eusebio.aguilera@gmail.com)
 * Created:   2011-11-23
 * Copyright: Eusebio Aguilera (http://code.google.com/p/mort/)
 * License:   BSD
 **************************************************************/

#include "MortMain.h"
#include <wx/msgdlg.h>
#include <wx/aboutdlg.h>
#include "EditPreferences.h"
#include "aux/MortSystem.h"
#include "tools/SkipfishToolHandler.h"

//(*InternalHeaders(MortFrame)
#include <wx/artprov.h>
#include <wx/bitmap.h>
#include <wx/intl.h>
#include <wx/image.h>
#include <wx/string.h>
//*)

//helper functions
enum wxbuildinfoformat {
    short_f, long_f };

wxString wxbuildinfo(wxbuildinfoformat format)
{
    wxString wxbuild(wxVERSION_STRING);

    if (format == long_f )
    {
#if defined(__WXMSW__)
        wxbuild << _T("-Windows");
#elif defined(__UNIX__)
        wxbuild << _T("-Linux");
#endif

#if wxUSE_UNICODE
        wxbuild << _T("-Unicode build");
#else
        wxbuild << _T("-ANSI build");
#endif // wxUSE_UNICODE
    }

    return wxbuild;
}

//(*IdInit(MortFrame)
const long MortFrame::idNewScan = wxNewId();
const long MortFrame::idMenuQuit = wxNewId();
const long MortFrame::idPreferences = wxNewId();
const long MortFrame::idMenuAbout = wxNewId();
const long MortFrame::ID_STATUSBAR1 = wxNewId();
//*)

BEGIN_EVENT_TABLE(MortFrame,wxFrame)
    //(*EventTable(MortFrame)
    //*)
END_EVENT_TABLE()

MortFrame::MortFrame(wxWindow* parent,wxWindowID id)
{
    //(*Initialize(MortFrame)
    wxMenuItem* MenuItem2;
    wxMenuItem* MenuItem1;
    wxMenu* Menu1;
    wxMenuBar* MenuBar1;
    wxMenu* Menu2;

    Create(parent, id, _("Mort"), wxDefaultPosition, wxDefaultSize, wxDEFAULT_FRAME_STYLE|wxMAXIMIZE_BOX|wxMINIMIZE_BOX|wxVSCROLL|wxHSCROLL|wxALWAYS_SHOW_SB, _T("id"));
    MenuBar1 = new wxMenuBar();
    Menu1 = new wxMenu();
    MenuItem3 = new wxMenuItem(Menu1, idNewScan, _("New\tCtrl-N"), _("Scan for vulnerabilities"), wxITEM_NORMAL);
    MenuItem3->SetBitmap(wxArtProvider::GetBitmap(wxART_MAKE_ART_ID_FROM_STR(_T("wxART_NEW")),wxART_MENU));
    Menu1->Append(MenuItem3);
    MenuItem1 = new wxMenuItem(Menu1, idMenuQuit, _("Quit\tAlt-F4"), _("Quit the application"), wxITEM_NORMAL);
    Menu1->Append(MenuItem1);
    MenuBar1->Append(Menu1, _("&Scan"));
    Menu3 = new wxMenu();
    MenuItem4 = new wxMenuItem(Menu3, idPreferences, _("Preferences"), wxEmptyString, wxITEM_NORMAL);
    Menu3->Append(MenuItem4);
    MenuBar1->Append(Menu3, _("&Edit"));
    Menu2 = new wxMenu();
    MenuItem2 = new wxMenuItem(Menu2, idMenuAbout, _("About\tF1"), _("Show info about this application"), wxITEM_NORMAL);
    Menu2->Append(MenuItem2);
    MenuBar1->Append(Menu2, _("Help"));
    SetMenuBar(MenuBar1);
    StatusBar1 = new wxStatusBar(this, ID_STATUSBAR1, 0, _T("ID_STATUSBAR1"));
    int __wxStatusBarWidths_1[1] = { -1 };
    int __wxStatusBarStyles_1[1] = { wxSB_NORMAL };
    StatusBar1->SetFieldsCount(1,__wxStatusBarWidths_1);
    StatusBar1->SetStatusStyles(1,__wxStatusBarStyles_1);
    SetStatusBar(StatusBar1);

    Connect(idNewScan,wxEVT_COMMAND_MENU_SELECTED,(wxObjectEventFunction)&MortFrame::OnNewScanSelected);
    Connect(idMenuQuit,wxEVT_COMMAND_MENU_SELECTED,(wxObjectEventFunction)&MortFrame::OnQuit);
    Connect(idPreferences,wxEVT_COMMAND_MENU_SELECTED,(wxObjectEventFunction)&MortFrame::OnEditPreferencesSelected);
    Connect(idMenuAbout,wxEVT_COMMAND_MENU_SELECTED,(wxObjectEventFunction)&MortFrame::OnAbout);
    Connect(wxID_ANY,wxEVT_CLOSE_WINDOW,(wxObjectEventFunction)&MortFrame::OnClose);
    //*)

    // Check default enviroment
    CheckDefaultEnviroment();

    // Try to load default profile
    LoadDefaultProfile();
}

MortFrame::~MortFrame()
{
    //(*Destroy(MortFrame)
    //*)
}

void MortFrame::OnQuit(wxCommandEvent& event)
{
    wxMessageDialog *dlg = new wxMessageDialog( this, _("Are you sure you want to quit the application?"), _("Question"), wxYES_NO);


    if ( dlg->ShowModal() == wxID_YES )
        this->Destroy();
}

void MortFrame::OnAbout(wxCommandEvent& event)
{
    wxAboutDialogInfo info;
    info.SetName(_("Mort"));
    info.SetVersion(_("0.1 Alpha"));
    info.SetDescription(_("This program use several tools for checking the security of web applications."));
    info.SetCopyright(_T("(C) 2011 Eusebio Aguilera <eusebio.aguilera@gmail.com>"));
    wxAboutBox(info);
}

void MortFrame::OnNewScanSelected(wxCommandEvent& event)
{
    // Use SkipfishToolHandler to launch a new skipfish scan
    SkipfishToolHandler *sk = new SkipfishToolHandler( &this->config );

    sk->ExecuteScan();
    //wxMessageDialog *dlg = new wxMessageDialog( this, _("Not implemented yet!"), _("Info"), wxOK);

    //dlg->ShowModal();
}

void MortFrame::OnClose(wxCloseEvent& event)
{
    wxMessageDialog *dlg = new wxMessageDialog( this, _("Are you sure you want to quit the application?"), _("Question"), wxYES_NO);


    if ( dlg->ShowModal() == wxID_YES )
        this->Destroy();
}

void MortFrame::OnEditPreferencesSelected(wxCommandEvent& event)
{
    EditPreferences *dlg = new EditPreferences( this, &this->config, -1 );

    dlg->ShowModal();

    // Reload new preferences
    this->defaultProfile = NULL;
    LoadDefaultProfile();
}

void MortFrame::CheckDefaultEnviroment()
{
    // Check default enviroment like default configuration dir structure

    if ( !MortSystem::CheckConfigDir() )
    {
        // Default config does not exists
        MortSystem::CreateConfigDir();
    }

    if ( !MortSystem::CheckProfileDir() )
    {
        // Default profile does not exists
        MortSystem::CreateProfileDir();
    }
}


void MortFrame::LoadDefaultProfile()
{
    // Try to load default profile
    if ( wxFileExists( MortSystem::GetProfileDir() + wxT("default.xml") ) ) {
        // File exists, so the program must load it
        this->defaultProfile = new wxXmlDocument();

        try {
            this->defaultProfile->Load( MortSystem::GetProfileDir() + wxT("default.xml") );
            this->config = MortSystem::LoadProfileFile( MortSystem::GetProfileDir() + wxT("default.xml") );
        } catch (std::exception e) {
            wxMessageBox( _("Default profile file may be corrupted!"), _("Warning"));

            // Delete default profile
            this->defaultProfile = NULL;
        }

        if ( defaultProfile->GetRoot()->GetName() != wxT("MortConf") ) {
            wxMessageBox( _("Default profile file may be corrupted!"), _("Warning"));

            // delete default profile
            this->defaultProfile = NULL;
        }
    }
}
